/*
 ***************************************************************************************
 *  Copyright (C) 2006 EsperTech, Inc. All rights reserved.                            *
 *  http://www.espertech.com/esper                                                     *
 *  http://www.espertech.com                                                           *
 *  ---------------------------------------------------------------------------------- *
 *  The software in this package is published under the terms of the GPL license       *
 *  a copy of which has been included with this distribution in the license.txt file.  *
 ***************************************************************************************
 */
package com.espertech.esper.common.internal.util;

import com.espertech.esper.common.client.scopetest.ScopeTestHelper;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Utility class for copying serializable objects via object input and output streams.
 */
public class SerializableObjectCopier {

    public static <T> T copy(T orig) throws IOException, ClassNotFoundException {
        SimpleByteArrayOutputStream fbos = new SimpleByteArrayOutputStream();
        ObjectOutputStream outStream = new ObjectOutputStream(fbos);
        try {
            outStream.writeObject(orig);
            outStream.flush();
        } finally {
            outStream.close();
        }

        ObjectInputStream inStream = new ObjectInputStreamWithTCCL(fbos.getInputStream());
        try {
            return (T) inStream.readObject();
        } finally {
            inStream.close();
        }
    }

    public static <T> T copyMayFail(T orig) {
        try {
            return copy(orig);
        } catch (Throwable t) {
            t.printStackTrace();
            ScopeTestHelper.fail();
        }
        throw new RuntimeException("Failed to copy serializable");
    }
}
